import { useEffect, useMemo, useRef, useContext } from 'react';
import { init, EChartsType } from 'echarts';
import classNames from 'classnames';
import { IChartsBaseData } from 'src/interface';
import { extractData } from 'src/utils/charts';
import { useThemeDark } from 'src/hooks/theme';
import { ContentContext } from 'src/context/ContentContext';

interface IProps {
  className?: string;
  style?: React.CSSProperties;
  data?: IChartsBaseData[];
  title?: string;
  height?: number | string;
  showLegend?: boolean;
  indicator: { name: string; max: number }[];
}

export default function RadarCharts(props: IProps) {
  const { className, style, data, title, height, showLegend, indicator } = props;
  const radarEl = useRef<HTMLDivElement | null>(null);
  const example = useRef<EChartsType | null>(null);

  const { dark } = useThemeDark();
  const contentSize = useContext(ContentContext);

  const chartsOptions = useMemo(() => {
    if (!data) return {};
    const { options, legend } = extractData(data);
    return {
      darkModel: dark,
      title: {
        text: title,
      },
      legend: {
        show: showLegend,
        data: legend,
      },
      tooltip: {
        trigger: 'item',
      },
      radar: {
        indicator,
      },
      series: [
        {
          type: 'radar',
          data: Object.keys(options).map((key) => {
            return {
              value: options[key].value,
              name: key,
              areaStyle: {
                color: options[key].areaColor,
              },
            };
          }),
        },
      ],
    };
  }, [data, dark, title, showLegend, indicator]);

  useEffect(() => {
    example.current && example.current.resize();
  }, [contentSize]);

  useEffect(() => {
    if (radarEl.current) {
      const charts = init(radarEl.current);
      example.current = charts;
    }
    example.current && example.current.setOption(chartsOptions);
    return () => {
      example.current && example.current.dispose();
    };
  }, [chartsOptions, dark]);

  return (
    <div
      ref={radarEl}
      className={classNames(className, 'w-[100%]')}
      style={{ ...style, height: height }}></div>
  );
}
